package com.wy.w_ui.ui.recyclerview;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class WAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;

    private LayoutInflater layoutInflater;
    private ArrayList<WDataItem<?, RecyclerView.ViewHolder>> dataSet = new ArrayList<>();
    /**
     * 装载列表上不同视图itemType
     */
    private SparseArray<WDataItem<?, RecyclerView.ViewHolder>> typeArrays = new SparseArray<>();

    public WAdapter(Context context) {
        mContext = context;
        layoutInflater = LayoutInflater.from(context);

    }

    /**
     * 添加单个item
     *
     * @param index  位置
     * @param item   DataItem
     * @param notify 是否刷新
     */
    public void addItem(int index, WDataItem<?, RecyclerView.ViewHolder> item, boolean notify) {
        //如果大于0说明需要添加到指定位置
        if (index > 0) {
            dataSet.add(index, item);
        } else {
            dataSet.add(item);
        }

        if (notify) {
            int notifyPosition = index > 0 ? index : dataSet.size() - 1;
            notifyItemChanged(notifyPosition);
        }
    }

    /**
     * 添加多条item
     *
     * @param items  dataItem
     * @param notify 是否刷新
     */
    public void addItems(List<WDataItem<?, RecyclerView.ViewHolder>> items, boolean notify) {
        //记录如果需要刷新的起始位置
        int start = dataSet.size();

        dataSet.addAll(items);

        if (notify) {
            notifyItemChanged(start, items.size());
        }
    }

    /**
     * 通过位置移除单条item
     *
     * @param index 位置
     * @return 被移除的item
     */
    public WDataItem removeItem(int index) {
        if (index > 0 && index < dataSet.size()) {
            WDataItem remove = dataSet.remove(index);
            notifyItemRemoved(index);
            return remove;
        } else {
            return null;
        }
    }

    /**
     * 通过item移除
     *
     * @param item dataItem
     */
    public void removeItem(WDataItem item) {
        if (item != null) {
            removeItem(dataSet.indexOf(item));
        }
    }

    @Override
    public int getItemViewType(int position) {
        WDataItem<?, RecyclerView.ViewHolder> dataItem = dataSet.get(position);
        int type = dataItem.getClass().hashCode();
        //如果没有包含这种类型的item,则添加进来
        if (typeArrays.indexOfKey(type) < 0) {
            typeArrays.put(type, dataItem);
        }
        return type;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        WDataItem<?, RecyclerView.ViewHolder> dataItem = typeArrays.get(viewType);
        View view = dataItem.getItemView(parent);
        if (view == null) {
            int layoutRes = dataItem.getItemLayoutRes();
            if (layoutRes < 0) {
                throw new RuntimeException("dataItem " + dataItem.getClass().getName() + "must override getItemVIew or getItemLayoutRes");
            }

            view = layoutInflater.inflate(layoutRes, parent, false);
        }
        //取出 DataItem 对应的 ViewHolder　的类型
        return createViewHolderInternal(dataItem.getClass(),view);
    }


    private RecyclerView.ViewHolder createViewHolderInternal(Class<? extends WDataItem> javaClass, View view) {
        //获取JavaClass对象的类型,也就是DataItem
        Type superClass = javaClass.getGenericSuperclass();

        if (superClass instanceof ParameterizedType) {
            //如果是参数泛型类型
            //获取泛型参数集合
            Type[] arguments = ((ParameterizedType) superClass).getActualTypeArguments();

            for (Type argument : arguments) {
                if (argument instanceof Class<?> && RecyclerView.ViewHolder.class.isAssignableFrom((Class<?>) argument)) {
                    try {
                        return (RecyclerView.ViewHolder) ((Class<?>) argument).getConstructor(View.class).newInstance(view);
                    } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return new RecyclerView.ViewHolder(view) {
        };
    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        WDataItem dataItem = dataSet.get(position);
        dataItem.onBindData(holder, position);

    }

    @Override
    public int getItemCount() {
        return dataSet.size();
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            final int spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
            ((GridLayoutManager) layoutManager).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if (position < dataSet.size()){
                        WDataItem dataItem = dataSet.get(position);
                        int  spanSize = dataItem.getSpanSize();
                        return spanSize <= 0 ? spanCount : spanSize;
                    }
                    return spanCount;
                }
            });

        }
    }

    public void refreshItem(WDataItem dataItem) {
        notifyItemChanged(dataSet.indexOf(dataItem));
    }

}
